package cn.bingoo.nginx;

import static cn.bingoo.h2.domain.Tables.NGINXSTATUS;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jooq.impl.Factory;
import org.jooq.util.h2.H2Factory;

import cn.bingoo.h2.domain.tables.records.NginxstatusRecord;
import cn.bingoo.swing.utils.Dbs;

public class NginxStatusClient {

    public ArrayList<String> collect(String url) throws IOException {
        System.out.println(url);
        HttpURLConnection conn = null;
        try {
            conn = HttpConnectionUtils.getConnection(url);
            conn.setRequestMethod("GET");
            String rspAsString = HttpConnectionUtils.getRspAsString(conn);
            System.out.println(rspAsString);
            Pattern pattern = Pattern.compile("\\b\\d+\\b");//, Pattern.MULTILINE);
            Matcher matcher = pattern.matcher(rspAsString);
            ArrayList<String> arrayList = new ArrayList<String>();
            arrayList.add(url);
            while (matcher.find()) {
                String group = matcher.group();
                arrayList.add(group);
            }
            return arrayList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public NginxstatusRecord save2Db(ArrayList<String> arrayList, Timestamp timestamp) {
        Connection conn = null;
        try {
            conn = NginxDbUtils.getConnectionWithTableAutoCreate();
            Factory create = new H2Factory(conn);
            int i = 0;
            NginxstatusRecord record = create.newRecord(NGINXSTATUS);
            record.setUrl(arrayList.get(i++));
            record.setTs(timestamp);
            record.setActives(Integer.parseInt(arrayList.get(i++)));
            record.setAccepts(Integer.parseInt(arrayList.get(i++)));
            record.setHandled(Integer.parseInt(arrayList.get(i++)));
            record.setRequests(Integer.parseInt(arrayList.get(i++)));
            record.setReading(Integer.parseInt(arrayList.get(i++)));
            record.setWriting(Integer.parseInt(arrayList.get(i++)));
            record.setWaiting(Integer.parseInt(arrayList.get(i++)));
            record.store();
            return record;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Dbs.closeQuietly(conn);
        }
        return null;
    }

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final NginxStatusClient nginxStatusClient = new NginxStatusClient();
        final Runnable beeper = new Runnable() {
            @Override
            public void run() {
                Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                for (String url : NginxConfig.URLS) {
                    ArrayList<String> collect;
                    try {
                        collect = nginxStatusClient.collect(url);
                        nginxStatusClient.save2Db(collect, timestamp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        scheduler.scheduleAtFixedRate(beeper, 0, 1, TimeUnit.MINUTES);
    }

    public static void main(String[] args) {
        new NginxStatusClient().beepForAnHour();
    }
}